package com.ruoyi.system.wnjk.service;

import com.ruoyi.system.wnjk.domain.dto.CartItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;

@Service
public class AppCartService {

    private static final String CART_KEY_PREFIX = "cart:";

    @Autowired
    private RedisTemplate redisTemplate;

    private HashOperations<String, String, CartItem> hashOperations;

    @PostConstruct
    private void init() {
        hashOperations = redisTemplate.opsForHash();
    }

    // 添加商品到购物车
    public void addToCart(String userId, CartItem cartItem) {
        // 校验 userId 是否为空
        if (userId == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }

        // 校验 cartItem 和 id 是否为空
        if (cartItem == null || cartItem.getId() == null ) {
            throw new IllegalArgumentException("商品信息不完整");
        }
        // Redis Key
        String cartKey = "cart:" + userId;
        String id = cartItem.getId();

        // 如果购物车中没有该商品，则新增
        redisTemplate.opsForHash().put(cartKey, id, cartItem);

    }

    // 获取用户的购物车数据
    public Map<String, CartItem> getCart(String userId) {
        String cartKey = "cart:" + userId;
        Map<String, CartItem> entries = hashOperations.entries(cartKey);
        return entries;
    }

    // 更新购物车中的商品数量
    public void updateCartItem(String userId, String id, int quantity) {
        String cartKey = "cart:" + userId;
        CartItem cartItem = hashOperations.get(cartKey, id);
        if (cartItem != null) {
            cartItem.setQuantity(quantity);
            hashOperations.put(cartKey, id, cartItem);
        }
    }

    // 删除购物车中的商品
    public void removeFromCart(String userId, String id) {
        String cartKey = "cart:" + userId;
        hashOperations.delete(cartKey, id);
    }

    // 清空购物车
    public void clearCart(String userId) {
        String cartKey = "cart:" + userId;
        redisTemplate.delete(cartKey);
    }

    //按商品id批量删除购物车中的数据
    public void deleteCartItems(String userId, List<String> itemIds) {
        String cartKey = "cart:" + userId;
        for (String itemId : itemIds) {
            hashOperations.delete(cartKey, itemId);
        }
    }
}
